package com.rickpan.service;

import com.rickpan.dto.dashboard.*;
import com.rickpan.entity.Favorite;
import com.rickpan.entity.FileInfo;
import com.rickpan.entity.FileShare;
import com.rickpan.entity.User;
import com.rickpan.repository.FileInfoRepository;
import com.rickpan.repository.FileShareRepository;
import com.rickpan.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Dashboard服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DashboardService {

    private final FileInfoRepository fileInfoRepository;
    private final FileShareRepository fileShareRepository;
    private final UserRepository userRepository;
    private final FavoriteService favoriteService;

    /**
     * 获取首页统计数据
     */
    public DashboardStatsDTO getDashboardStats(Long userId) {
        log.info("获取用户 {} 的统计数据", userId);

        // 获取用户信息
        Optional<User> userOpt = userRepository.findById(userId);
        if (!userOpt.isPresent()) {
            throw new RuntimeException("用户不存在");
        }
        User user = userOpt.get();

        // 统计文件数量（非文件夹且未删除）
        Long totalFiles = fileInfoRepository.countByOwnerIdAndIsDirectoryAndIsDeleted(userId, false, false);

        // 统计文件夹数量（文件夹且未删除）
        Long totalFolders = fileInfoRepository.countByOwnerIdAndIsDirectoryAndIsDeleted(userId, true, false);

        // 统计分享数量
        Long shareCount = fileShareRepository.countByUserId(userId);

        return DashboardStatsDTO.builder()
                .totalFiles(totalFiles != null ? totalFiles : 0L)
                .totalFolders(totalFolders != null ? totalFolders : 0L)
                .shareCount(shareCount != null ? shareCount : 0L)
                .storageUsed(user.getStorageUsed() != null ? user.getStorageUsed() : 0L)
                .storageQuota(user.getStorageQuota() != null ? user.getStorageQuota() : 5368709120L) // 5GB默认
                .build();
    }

    /**
     * 获取最近文件
     */
    public List<FileInfo> getRecentFiles(Long userId, Integer limit) {
        log.info("获取用户 {} 的最近文件，限制: {}", userId, limit);

        PageRequest pageRequest = PageRequest.of(0, limit, Sort.by(Sort.Direction.DESC, "updatedAt"));
        List<FileInfo> recentFiles = fileInfoRepository.findByOwnerIdAndIsDirectoryAndIsDeletedOrderByUpdatedAtDesc(
                userId, false, false, pageRequest);
        return recentFiles != null ? recentFiles : new ArrayList<>();
    }

    /**
     * 获取收藏文件
     */
    public List<FileInfo> getFavoriteFiles(Long userId, Integer limit) {
        log.info("获取用户 {} 的收藏文件，限制: {}", userId, limit);

        try {
            // 获取最近收藏的记录
            List<Favorite> favorites = favoriteService.getRecentFavorites(userId, limit);

            // 转换为FileInfo列表
            List<FileInfo> favoriteFiles = new ArrayList<>();
            for (Favorite favorite : favorites) {
                Optional<FileInfo> fileOpt = fileInfoRepository.findById(favorite.getFileId());
                if (fileOpt.isPresent() && !fileOpt.get().getIsDeleted()) {
                    favoriteFiles.add(fileOpt.get());
                }
            }

            return favoriteFiles;
        } catch (Exception e) {
            log.error("获取收藏文件失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 获取文件类型统计
     */
    public List<FileTypeStatsDTO> getFileTypeStats(Long userId) {
        log.info("获取用户 {} 的文件类型统计", userId);

        // 获取用户所有文件
        List<FileInfo> files = fileInfoRepository.findByOwnerIdAndIsDirectoryAndIsDeleted(userId, false, false);

        // 按MIME类型分组统计
        Map<String, List<FileInfo>> groupedFiles = files.stream()
                .collect(Collectors.groupingBy(file -> file.getMimeType() != null ? file.getMimeType() : "unknown"));

        return groupedFiles.entrySet().stream().map(entry -> {
            String mimeType = entry.getKey();
            List<FileInfo> fileList = entry.getValue();

            // 根据MIME类型确定分类和图标
            String category = categorizeFileType(mimeType);
            String icon = getIconForCategory(category);
            String color = getColorForCategory(category);

            long count = fileList.size();
            long size = fileList.stream().mapToLong(file -> file.getFileSize() != null ? file.getFileSize() : 0L).sum();

            return FileTypeStatsDTO.builder()
                    .name(category)
                    .count(count)
                    .size(size)
                    .icon(icon)
                    .color(color)
                    .build();
        }).collect(Collectors.groupingBy(FileTypeStatsDTO::getName))
          .entrySet().stream()
          .map(entry -> {
              List<FileTypeStatsDTO> group = entry.getValue();
              return FileTypeStatsDTO.builder()
                      .name(entry.getKey())
                      .count(group.stream().mapToLong(FileTypeStatsDTO::getCount).sum())
                      .size(group.stream().mapToLong(FileTypeStatsDTO::getSize).sum())
                      .icon(group.get(0).getIcon())
                      .color(group.get(0).getColor())
                      .build();
          }).collect(Collectors.toList());
    }

    /**
     * 获取分享统计
     */
    public ShareStatsDTO getShareStats(Long userId) {
        log.info("获取用户 {} 的分享统计", userId);

        List<FileShare> shares = fileShareRepository.findByUserId(userId);

        long total = shares.size();
        long active = shares.stream().filter(share -> "ACTIVE".equals(share.getStatus())).count();
        long expired = shares.stream().filter(share -> "EXPIRED".equals(share.getStatus())).count();
        long disabled = shares.stream().filter(share -> "DISABLED".equals(share.getStatus())).count();
        long totalViews = shares.stream().mapToLong(share -> share.getAccessCount() != null ? share.getAccessCount() : 0L).sum();

        return ShareStatsDTO.builder()
                .total(total)
                .active(active)
                .expired(expired)
                .disabled(disabled)
                .totalViews(totalViews)
                .build();
    }

    /**
     * 获取首页完整数据
     */
    public DashboardDataDTO getDashboardData(Long userId) {
        log.info("获取用户 {} 的首页完整数据", userId);
        
        return DashboardDataDTO.builder()
                .stats(getDashboardStats(userId))
                .recentFiles(getRecentFiles(userId, 5))
                .favoriteFiles(getFavoriteFiles(userId, 5))
                .fileTypeStats(getFileTypeStats(userId))
                .shareStats(getShareStats(userId))
                .build();
    }

    /**
     * 根据MIME类型分类文件
     */
    private String categorizeFileType(String mimeType) {
        if (mimeType == null) return "others";
        
        if (mimeType.startsWith("image/")) return "images";
        if (mimeType.startsWith("video/")) return "videos";
        if (mimeType.startsWith("audio/")) return "audios";
        if (mimeType.contains("pdf") || mimeType.contains("document") || 
            mimeType.contains("text") || mimeType.contains("word") || 
            mimeType.contains("excel") || mimeType.contains("powerpoint")) {
            return "documents";
        }
        return "others";
    }

    /**
     * 获取分类对应的图标
     */
    private String getIconForCategory(String category) {
        switch (category) {
            case "images": return "Picture";
            case "videos": return "VideoPlay";
            case "audios": return "Headphones";
            case "documents": return "Document";
            default: return "Files";
        }
    }

    /**
     * 获取分类对应的颜色
     */
    private String getColorForCategory(String category) {
        switch (category) {
            case "images": return "#67c23a";
            case "videos": return "#e6a23c";
            case "audios": return "#f56c6c";
            case "documents": return "#409eff";
            default: return "#909399";
        }
    }
}
